<?php
function messages(){
	global $_SGET,$_SPOST,$_SREQUEST;
	global $auid,$valid;
	/*get allready existing messages*/
	if ($_SERVER['REQUEST_METHOD']=="GET"){

		$postid= $_SGET['postid'];

		/*default order DESC*/
		if (isset( $_SGET['order'])){
			$order2=$order;
		}else{
			$order2="DESC";
		}

		/*default sort timestamp*/
		if (isset( $_SGET['sortby'])){
			$sortby2=$sortby;
		}else{
			$sortby2="timestamp";
		}
		if (!$startat){
			$startat=0;
		}
		$stopat=$startat+30;

		$where="WHERE 1";
		/*default are all messages to and from the user*/
		if ($valid){
			if($_REQUEST['action']=='from'){
				$where.= " AND `from`=$auid";
			}else if($_REQUEST['action']=='to'){
				$where.= " AND `to`=$auid";
			}else{
				$where.= " AND (`to`=$auid OR `from`=$auid)";
			}
			if ($postid){
				$where.=" AND id=$postid";
			}
			$query="SELECT * FROM messages ".$where." ORDER BY ".$sortby2." ".$order2." LIMIT ".$startat." , ".$stopat;

			$result=mysql_query($query);

			$rows = array();
			while($r = mysql_fetch_assoc($result)){
				$rows[] = $r;
			}
			print json_encode($rows);

		}else{
			header("HTTP/1.0 401 UNAUTHORIZED");
		}
	}

	/*post new message*/
	if ($_SERVER['REQUEST_METHOD']=="POST"){
		if ($valid){
			$username 	= $_SPOST['username'];
			$subject 	= $_SPOST['subject'];
			$msg 		= $_SPOST['msg'];
			$type 		= $_SPOST['type'];
			if (!isset($subject)){
				$subject="subject";
			}
			/*Do the user exsist?*/
			$query="SELECT * FROM users WHERE username='$username'";
			//echo $username;
			//echo $_SPOST['username'];
			$result=mysql_query($query);
			if (mysql_num_rows($result)){
				$rmsg = mysql_fetch_assoc($result);
				/*get his user id'*/
				$id=$rmsg['id'];
				/*friend request*/
				if ($type==1){
					$subject="Friend request";
					$msg=null;
					$result= mysql_query("INSERT INTO `friendrequests` (`id`,`f1`,`f2`) VALUES (NULL,'$auid','$id')");
				}
				$query = "INSERT INTO messages (`id`, `from`, `to`, `subject`, `text`, `timestamp`, `read`, `type`) VALUES (NULL , '$auid', '$id', '$subject', '$msg',NULL, 0,'$type')";
				$result = mysql_query ($query);
				header("HTTP/1.0 200 OK");
			}else{
				/*the user don't exist*/
				header("HTTP/1.0 400 $query");
			}
		}else{
			header("HTTP/1.0 401 UNAUTHORIZED");
		}
	}
	/*delete a message*/
	if ($_SERVER['REQUEST_METHOD']=="DELETE"){
		if($valid){
			$id =  $_SGET['id'];
			$query="DELETE FROM messages WHERE id=$id AND `to`=$auid";
			$result = mysql_query ($query);
			if (mysql_affected_rows()){
				header("HTTP/1.0 200 OK");
			}else{
				header("HTTP/1.0 404 NOT FOUND");
			}
		}else{
			header("HTTP/1.0 401 UNAUTHORIZED");
		}
	}
}
?>